#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月25日

@author: chenyongbing
'''
import sys,os,datetime,re

#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import copy
sys.path.append(os.path.join(current_dir,'../../'))
from base.localConfig import baseLocalConfig
import logging
from base.mofi_datas import myMofiDatas
from base.retail_datas import myRetailDatas
from base.time_method import myTimeMethod
from base.PyExportFile import myExportFile

class RecordApOnlineTime(object):
    '''
        记录设备在线时长
    '''


    def __init__(self):
        '''
        Constructor
        '''
    def get_online_time_by_devices(self,devices=[],startTime=None,endTime=None):
        datas = {}
        for device in devices:
            total_time = myMofiDatas.stat_online_time(device=device, startTime=startTime, endTime=endTime)
            datas[device] = round(total_time/60.0,2)
        return datas
    
    def export_online_time_by_comp(self,comp_group=None,shop_groups=[],comp_id=None,startTime=None,endTime=None):
        
        groupsInfos = myRetailDatas.get_groups_info_by_comp(comp_id=comp_id, groups=shop_groups,comp_group=comp_group)
        datas = copy.copy(groupsInfos)
        for group,groupInfo in groupsInfos.iteritems():
            group_name = groupInfo['name']
            serial_number = groupInfo['serial_number']
            province = groupInfo['province']
            city = groupInfo['city']
            dist = groupInfo['dist']
            try:
                groupDevices = myRetailDatas.get_devices_by_group(groups=[int(group)])
                
                devices =groupDevices[int(group)]
            except:
                logging.error('can not found any device in group %s'%group)
                del datas[group]
                continue
            online_time_datas = self.get_online_time_by_devices(devices=devices, startTime=startTime, endTime=endTime)
            datas[group]['online_time_datas'] = online_time_datas
        return datas
    
    
    def get_online_time_datas_with_lenovo_temp(self,comp_group=None,shop_groups=[],comp_id=None,startTime=None,endTime=None):
        '''联想模板 CSV'''
        alldatas = []
        fields = [u'日期',u'星期',u'名称',u'门店',u'品牌',u'店铺编码',u'归属省份',u'归属城市',u'AP在线时长/日（单位：分钟）']
        alldatas.append(fields)
        
        days = myTimeMethod.get_slist_between_st_et(startTime, endTime)
        for day in days:
            weekday = myTimeMethod.get_weekday(day)

                
            if len(shop_groups)!=0:
                datas =self.export_online_time_by_comp(comp_group=comp_group, shop_groups=shop_groups,startTime=day, endTime = day)
            else:
                datas = self.export_online_time_by_comp(comp_group=comp_group, startTime=day, endTime = day)
            for group , groupInfo in datas.iteritems():
                group_name = groupInfo['name']
                serial_number = groupInfo['serial_number']
                province = groupInfo['province']
                city = groupInfo['city']
                online_time_datas = groupInfo['online_time_datas']
                try:
                    shop_name,shop_brand = group_name.split('-')
                except:
                    shop_name = shop_brand=''
                total_online_time = 0
                for device , online_time in online_time_datas.iteritems():
                    total_online_time+=online_time
                
                values = [day,weekday,group_name,shop_name,shop_brand,serial_number,province,city,str(total_online_time)]
                alldatas.append(values)
        return alldatas
    
    def export_online_time(self,comp_group=None,shop_groups=[],comp_id=None,startTime=None,endTime=None,export_file='',temp='lenovo_temp'):
        datas = []
        if temp == 'lenovo_temp':
            datas = self.get_online_time_datas_with_lenovo_temp(comp_group=comp_group,shop_groups=shop_groups, comp_id=comp_id, startTime=startTime, endTime=endTime)
        myExportFile.export_online_time(datas, export_file)
        
                
    
myRecordStaOnlineTime = RecordApOnlineTime()
            
if __name__ == '__main__':
    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--startTime',metavar=u"starttime",default=None)
    parser.add_argument('--endTime',metavar=u"endtime",default=None)
    parser.add_argument('--rule',metavar=u"rule",default=None)
    parser.add_argument('--comp_group',metavar='company group',default=None)
    parser.add_argument('--shop_group',metavar='shop group',default=None)
    parser.add_argument('--format',metavar='file format:csv,xlsx,xls',default='csv')
    args = parser.parse_args()
    startTime=args.startTime
    endTime=args.endTime
    comp_group = args.comp_group
    shop_group = args.shop_group
    rule = args.rule
    format = args.format
    if comp_group!=None:
        file_name = myRetailDatas.get_comp_name(shop_group=comp_group).encode("utf-8")
        shop_groups = []
        #comp_groups = [comp_group]
    elif shop_group!=None:
        file_name = myRetailDatas.get_group_name(group=shop_group).encode("utf-8")
        #comp_groups = None
        shop_groups = [shop_group]
    else:
        logging.error('You Must Enter One from comp_group and shop_group.')    
    
    export_file=os.path.join(current_dir,'../report/%s设备在线时长报表(%s-%s).%s'%(file_name,re.sub('-','.',startTime),re.sub('-','.',endTime),format))
        
    myRecordStaOnlineTime.export_online_time(comp_group=comp_group,shop_groups=shop_groups,startTime=startTime,endTime=endTime,export_file=export_file, temp=rule)
    
    #myRecordStaOnlineTime.export_online_time_with_lenovo_temp(comp_groups=comp_groups,startTime=startTime,endTime=endTime,export_file=export_file)
    
    
    
    